<?php 
class ControllerCategory extends Controller {  
	function index() { 
		$cart     =& $this->locator->get('cart');
		$config   =& $this->locator->get('config');
		$currency =& $this->locator->get('currency');
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');
		$image    =& $this->locator->get('image');
		$module   =& $this->locator->get('module');
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$session  =& $this->locator->get('session');
		$tax      =& $this->locator->get('tax');
		$template =& $this->locator->get('template');
		$url      =& $this->locator->get('url');
		
		// Q: Added support for Add to Cart
        if ($request->isPost() && $request->has('product_id', 'post')) {
			
			// Get Qty
            $qty = 1;
            if ($request->has('quantity', 'post') && $request->get('quantity', 'post')) {
                $qty = $request->get('quantity', 'post');
            }
            
            // Check that Min Order Qty is greater or equal to the current qty and adjust if necessary
            //if($request->get('min_ord_qty', 'post') != NULL && ($request->get('min_ord_qty', 'post') > $qty)) {
            //    $qty = $request->get('min_ord_qty', 'post');
            //}
            
            $cart->add($request->get('product_id', 'post'), $qty, $request->get('option', 'post'));
            
            $response->redirect($url->ssl('cart'));
		}
		
		//pagination
		$set=$request->has('path')?'category.'.$request->gethtml('path').'.page':'category.page';
        $session->set($set, $request->has('page')?$request->get('page'):1);

		$language->load('controller/category.php');
	
		$category_info = $database->getRow("select distinct name, description from category c left join category_description cd on (c.category_id = cd.category_id) where c.status = '1' and c.category_id = '".(int)((!$request->gethtml('path')) ? '0':(int)end(explode('_', $request->gethtml('path'))))."' and cd.language_id = '".(int)$language->getId()."'");
		
		$view = $this->locator->create('template');
		
		$view->set('tpl', $template);

      	$view->set('button_continue', $language->get('button_continue'));

      	$view->set('continue', $url->href('home'));

		if ($category_info) {
	  		$template->set('title', $category_info['name']);
        	
			$view->set('heading_title', $category_info['name']);

      		$breadcrumb = array();

      		$breadcrumb[] = array(
        		'href'      => $url->href('home'),
        		'text'      => $language->get('text_home'),
        		'separator' => FALSE
      		);

      		foreach (explode('_', $request->gethtml('path')) as $category_id) {
        		$result = $database->getRow("select cd.name, c.path from category c left join category_description cd on (c.category_id = cd.category_id) where c.status = '1' and c.category_id = '".(int)$category_id."' and cd.language_id = '".(int)$language->getId()."'");

        		$breadcrumb[] = array(
          			'href'      => $url->href('category', FALSE, array('path' => $result['path'])),
          			'text'      => $result['name'],
          			'separator' => $language->get('text_separator')
        		);
      		}

			$view->set('breadcrumbs', $breadcrumb);

			if (($database->countRows("select * from product_to_category p2c left join product p on p2c.product_id = p.product_id where p.status = '1' and p2c.category_id = '".(int)end(explode('_', $request->gethtml('path')))."'")) || ($database->countRows("select * from category where parent_id = '".(int)end(explode('_', $request->gethtml('path')))."'"))) {

        		$category_data = array();
                
                //See http://code.google.com/p/open-cart/issues/detail?id=19
                $results = $database->getRows("select * from category c left join category_description cd on (c.category_id = cd.category_id) left join image i on (c.image_id = i.image_id) where c.status = '1' and c.parent_id = '".(int)(!$request->gethtml('path') ? '0' : (int)end(explode('_', $request->gethtml('path'))))."' and cd.language_id = '".(int)$language->getId()."' order by sort_order");
				
        		foreach ($results as $result) {
          			$category_data[] = array(
            			'name'  => $result['name'],
            			'href'  => $url->href('category', FALSE, array('path' => ($request->gethtml('path')) ? $request->gethtml('path').'_'.$result['category_id'] : $result['category_id'])),
                        'thumb' => (isset($result['filename']) && file_exists(DIR_IMAGE.$result['filename'])) ? $image->resize($result['filename'], $config->get('config_image_width'), $config->get('config_image_height')) : NULL
          			);
        		}

        		$view->set('categories', $category_data);
				
				$product_data = array();
        		
				$results = $database->getRows($database->splitQuery("select * from product p left join product_description pd on (p.product_id = pd.product_id) left join product_to_category p2c on (p.product_id = p2c.product_id) left join image i on (p.image_id = i.image_id) where status = '1' and language_id = '".(int)$language->getId()."' and p2c.category_id = '".(int)end(explode('_', $request->gethtml('path')))."' and p.date_available < now() and p.status = '1' order by p.sort_order, pd.name", ($request->has('path') ? $session->get('category.'.$request->gethtml('path').'.page') : $session->get('category.page')), $config->get('config_max_rows')));

        		foreach ($results as $product_info) {
          			$query = array(
            			'path'       => $request->gethtml('path'),
            			'product_id' => $product_info['product_id']
          			);

          			
          			$options = array();

          			$product_special = $database->getRow("SELECT * FROM product_special WHERE product_id = '" . (int)$product_info['product_id'] . "' AND date_start < NOW() AND date_end > NOW() and status = '1'");
					
					$price = $product_info['price'];
								
					if ($product_special && $product_special['prefix']) {
						if ($product_special['prefix'] == '%') {
							$price -= $price * ($product_special['discount']/100);
						} elseif ($product_special['prefix'] == '-') {
							$price -= $product_special['discount'];
						} else {
							$price = $product_special['discount'];
						}
					}
	
      				$resopts = $database->getRows("select * from product_to_option where product_id = '" . (int)$product_info['product_id'] . "' order by sort_order");

      				foreach ($resopts as $resopt) {
        				$options[$resopt['option_id']][] = array(
          					'product_to_option_id' => $resopt['product_to_option_id'],
          					'option_value_id'      => $resopt['option_value_id'],
          					'price'                => $resopt['price'],
          					'prefix'               => $resopt['prefix']
        				);
      				}

      				$option_data = array();

      				foreach ($options as $key => $values) {
        				$option_value_data = array();

        				foreach ($values as $value) {
          					$option_value_info = $database->getRow("select * from option_value where option_value_id = '" . (int)$value['option_value_id'] . "' and option_id = '" . (int)$key . "' and language_id = '" . (int)$language->getId() . "'");

          					$option_value_data[] = array(
            					'product_to_option_id' => $value['product_to_option_id'],
            					'option_value_id'      => $value['option_value_id'],
            					'name'                 => $option_value_info['name'],
            					'price'                => (($value['price'] != '0.00') ? $currency->format($tax->calculate($value['price'], $product_info['tax_class_id'], $config->get('config_tax'))) : null),
            					'prefix'               => $value['prefix']
          					);
        				}

        				$option = $database->getRow("select * from `option` where option_id = '" . (int)$key . "' and language_id = '" . (int)$language->getId() . "'");

        				$option_data[] = array(
          					'option_id' => $key,
          					'name'      => $option['name'],
          					'value'     => $option_value_data
        				);
      				}
    
          			
          			$product_data[] = array(
            			'product_id'	=> $product_info['product_id'],
            			'name'			=> $product_info['name'],
            			'description'	=> substr(strip_tags($product_info['description']),0,180) . '...',
            			'model'			=> $product_info['model'],
            			'quantity'		=> $product_info['quantity'],
            			'min_qty'		=> $product_info['min_qty'],
            			'href'			=> $url->href('product', FALSE, $query),
            			'thumb'			=> $image->resize($product_info['filename'], $config->get('config_image_width_category'), $config->get('config_image_height_category')),
            			'price'			=> $currency->format($tax->calculate($price, $product_info['tax_class_id'], $config->get('config_tax'))),
            			'price_old'		=> ($product_special['prefix']) ? $currency->format($tax->calculate($product_info['price'], $product_info['tax_class_id'], $config->get('config_tax'))) : NULL,
            			'options'		=> $option_data
          			);
          			
        		}

        		$view->set('products', $product_data);

				$view->set('description', $category_info['description']);

        		$view->set('text_product', $language->get('text_product'));
        		$view->set('text_options', $language->get('text_options'));
        		$view->set('text_model', $language->get('text_model'));
        		$view->set('text_quantity', $language->get('text_quantity'));
        		$view->set('text_results', $language->get('text_results', $database->getFrom(), $database->getTo(), $database->getTotal()));

        		$view->set('button_add_to_cart', $language->get('button_add_to_cart'));
        		
	      		$view->set('entry_page', $language->get('entry_page'));
      			
				$view->set('action', $url->href('category', FALSE, array('path' => $request->gethtml('path'))));
				
				$view->set('ajaxadd', $config->get('config_ajaxadd_category'));
				
				$view->set('page', ($request->has('path') ? $session->get('category.'.$request->gethtml('path').'.page') : $session->get('category.page')));
							
				$page_data = array();

      			for ($i = 1; $i <= $database->getPages(); $i++) {
					$query=array('path' => $request->gethtml('path'));
					if ($i > 1) $query['page'] = $i;
        			$page_data[] = array(
          				'text'  => $language->get('text_pages', $i, $database->getPages()),
						'href'	=> $url->href('category', FALSE, $query),
          				'value' => $i
        			);
      			}

      			$view->set('pages', $page_data);
			
				$template->set('content', $view->fetch('content/category.tpl'));
			
				//$template->set($module->fetch());
				
    			//$response->set($template->fetch('layout.tpl')); 				
      		} else {
        		$view->set('text_error', $language->get('text_empty'));

				$template->set('content', $view->fetch('content/error.tpl'));
      		}
    	} else {
	  		$template->set('title', $language->get('text_error'));	
 
      		$view->set('heading_title', $language->get('text_error'));

      		$view->set('text_error', $language->get('text_error'));
	  
	  		$template->set('content', $view->fetch('content/error.tpl'));
		}

		$template->set($module->fetch());
		
		$view->set('latest', $template->get('latest'));

    	$response->set($template->fetch('layout.tpl')); 	
  	}
	
	function page() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$session  =& $this->locator->get('session');
		$url      =& $this->locator->get('url');

		$query=array();

		$query['path'] = $request->gethtml('path');

		//backwards compat pagination
      	if ($request->has('page', 'post')) {
			$i=(int)$request->get('page', 'post');
			if ($i > 1) $query['page'] = $i;
      	}

		$response->redirect($url->href('category', FALSE, $query));
	}
}
?>
